package com.tdam2011.grupo05.ui.activities;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

import com.tdam2011.grupo05.R;
import com.tdam2011.grupo05.R.array;
import com.tdam2011.grupo05.R.drawable;
import com.tdam2011.grupo05.R.id;
import com.tdam2011.grupo05.R.layout;
import com.tdam2011.grupo05.R.string;
import com.tdam2011.grupo05.entidades.ComparadorContacto;
import com.tdam2011.grupo05.entidades.LogAccion;
import com.tdam2011.grupo05.ui.quickaction.ActionItem;
import com.tdam2011.grupo05.ui.quickaction.QuickAction;

public class LogActivity extends ListActivity {

	private final int DIALOG_ORDENAR = 1;

	LogAdapter adapter;
	QuickAction mQuickAction;
	ImageView mMoreIv = null;
	ArrayList<LogAccion> acciones = new ArrayList<LogAccion>();
	ArrayList<LogAccion> filtrados = new ArrayList<LogAccion>();
	String contactoNom;
	SharedPreferences settingOrden;
	boolean filtroFlag = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.log_activity);
		Spinner s = (Spinner) findViewById(R.id.spinner);

		ArrayAdapter<CharSequence> adapterSpinner = ArrayAdapter
				.createFromResource(this, R.array.filtroAcciones,
						android.R.layout.simple_spinner_item);
		adapterSpinner
				.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
		s.setAdapter(adapterSpinner);

		settingOrden = getPreferences(MODE_PRIVATE);
		String idContacto = getIntent().getStringExtra("idContacto");
		ArrayList<String> emails = getIntent()
				.getStringArrayListExtra("emails");
		contactoNom = getIntent().getStringExtra("contacto");

		Typeface tf = Typeface.createFromAsset(getAssets(),
				"fonts/BIMINR__.TTF");
		TextView empty = (TextView) findViewById(android.R.id.empty);
		empty.setTypeface(tf);

		TextView titulo = (TextView) findViewById(R.id.texto_titulo);
		titulo.setTypeface(tf);
		titulo.setTextSize(22);

		ImageView ordenar = (ImageView) findViewById(R.id.ordenar_titulo);
		ordenar.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				onCreateDialog(DIALOG_ORDENAR);
			}
		});

		// Llamar action item
		ActionItem callAction = new ActionItem();
		callAction.setTitle("Llamar");
		callAction.setIcon(getResources().getDrawable(
				R.drawable.ic_quick_llamada));

		// Enviar Sms action item
		ActionItem smsAction = new ActionItem();
		smsAction.setTitle("Sms");
		smsAction.setIcon(getResources().getDrawable(R.drawable.ic_quick_sms));

		// Enviar E-mail action item
		ActionItem mailAction = new ActionItem();
		mailAction.setTitle("E-mail");
		mailAction
				.setIcon(getResources().getDrawable(R.drawable.ic_quick_mail));

		// Servicio Web action item
		ActionItem webAction = new ActionItem();
		webAction.setTitle("Web");
		webAction.setIcon(getResources().getDrawable(R.drawable.ic_quick_web));

		mQuickAction = new QuickAction(this);

		mQuickAction.addActionItem(callAction);
		mQuickAction.addActionItem(smsAction);
		mQuickAction.addActionItem(mailAction);
		mQuickAction.addActionItem(webAction);

		// setup the action item click listener
		mQuickAction
				.setOnActionItemClickListener(new QuickAction.OnActionItemClickListener() {
					@Override
					public void onItemClick(int pos) {

						if (pos == 0) {

						} else if (pos == 1) {

						} else if (pos == 2) {

						} else if (pos == 3) {

						}
					}
				});

		// setup on dismiss listener, set the icon back to normal
		// mQuickAction.setOnDismissListener(new PopupWindow.OnDismissListener()
		// {
		// @Override
		// public void onDismiss() {
		// mMoreIv.setImageResource(R.drawable.ic_list_more);
		// }
		// });

		// LOG DE LLAMADAS
		// MUESTRA SOLO LAS ACCIONES DEL CONTACTO SELECCIONADO EN LA
		// ContactosActivity
		long id;
		DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");

		Cursor phones = getContentResolver().query(Phone.CONTENT_URI, null,
				Phone.CONTACT_ID + " = " + idContacto, null, null);
		while (phones.moveToNext()) {
			String number = phones.getString(
					phones.getColumnIndex(Phone.NUMBER)).replace("-", "");
			Cursor cursor = getContentResolver().query(android.provider.CallLog.Calls.CONTENT_URI, null,android.provider.CallLog.Calls.NUMBER + " = " + number,	null, android.provider.CallLog.Calls.DATE + " DESC");

			startManagingCursor(cursor);

			id = 0;

			while (cursor.moveToNext()) {
				String _contacto = cursor.getString(cursor.getColumnIndex(android.provider.CallLog.Calls.CACHED_NAME));
				String _telefono = cursor.getString(cursor.getColumnIndex(android.provider.CallLog.Calls.NUMBER));
				int _icono = cursor.getInt(cursor.getColumnIndex(android.provider.CallLog.Calls.TYPE));
				Date fecha = new Date(cursor.getLong(cursor.getColumnIndex(android.provider.CallLog.Calls.DATE)));
				String _fecha = formatter.format(fecha);

				int imagen;

				switch (_icono) {
				case android.provider.CallLog.Calls.INCOMING_TYPE:
					imagen = R.drawable.ic_call_log_list_incoming_call;
					break;
				case android.provider.CallLog.Calls.MISSED_TYPE:
					imagen = R.drawable.ic_call_log_list_missed_call;
					break;
				case android.provider.CallLog.Calls.OUTGOING_TYPE:
					imagen = R.drawable.ic_call_log_list_outgoing_call;
					break;
				default:
					imagen = R.drawable.ic_call_log_list_incoming_call;
					break;
				}
				id++;

				LogAccion llamada = new LogAccion();

				llamada.set_id(id);
				if (_contacto != null)
					llamada.setNombreContacto(_contacto);
				else
					llamada.setNombreContacto(_telefono);
				llamada.set_fecha(_fecha);
				llamada.set_telfono(_telefono);
				llamada.set_tipoLlamada(imagen);

				acciones.add(llamada);

			}

			// LOG DE SMS
			// INBOX
			number = phones.getString(
					phones.getColumnIndex(Phone.NUMBER));
			Cursor c = getContentResolver().query(
					Uri.parse("content://sms/inbox"), null,
					"address" + " = " + number, null, null);
			startManagingCursor(c);
			id = 0;

			while (c.moveToNext()) {
				Toast toast = Toast.makeText(this, c.getString(c.getColumnIndex("address")), Toast.LENGTH_SHORT);
				toast.show();
				String _contacto = c.getString(c.getColumnIndex("person"));
				String _telefono = c.getString(c.getColumnIndex("address"));
				Date fecha = new Date(c.getLong(c.getColumnIndex("date")));
				String _fecha = formatter.format(fecha);

				int imagen = R.drawable.ic_sms_log_list_incoming_sms;

				id++;
				LogAccion sms = new LogAccion();
				sms.set_id(id);
				if (_contacto != null)
					sms.setNombreContacto(_contacto);
				else
					sms.setNombreContacto(_telefono);
				sms.set_fecha(_fecha);
				sms.set_telfono(_telefono);
				sms.set_tipoLlamada(imagen);
				acciones.add(sms);
			}

			// SENT
			Cursor env = getContentResolver().query(
					Uri.parse("content://sms/sent"), null,
					"address" + " = " + number, null, null);
			startManagingCursor(env);
			id = 0;

			while (env.moveToNext()) {
				String _contacto = env.getString(env.getColumnIndex("person"));
				String _telefono = env.getString(env.getColumnIndex("address"));
				Date fecha = new Date(env.getLong(env.getColumnIndex("date")));
				String _fecha = formatter.format(fecha);
				
				int imagen = R.drawable.ic_sms_log_list_outgoing_sms;

				id++;
				LogAccion sms2 = new LogAccion();
				sms2.set_id(id);
				if (_contacto != null)
					sms2.setNombreContacto(_contacto);
				else
					sms2.setNombreContacto(_telefono);
				sms2.set_fecha(_fecha);
				sms2.set_telfono(_telefono);
				sms2.set_tipoLlamada(imagen);
				acciones.add(sms2);
			}

			// LOG DE SMS
		}
		phones.close();

		// LOG DE MMS
		Cursor curPdu = getContentResolver().query(
				Uri.parse("content://mms/outbox"), null, null, null, null);
		startManagingCursor(curPdu);
		id = 0;
		while (curPdu.moveToNext()) {

			String idMMS = curPdu.getString(curPdu.getColumnIndex("_id"));
			Date fecha = new Date(
					(curPdu.getLong(curPdu.getColumnIndex("date")) * 1000));
			String date = formatter.format(fecha);

			int imagen = R.drawable.ic_mms_log_list_outgoing_mms;

			id++;
			LogAccion mms = new LogAccion();
			mms.set_id(id);

			Uri uriAddr = Uri.parse("content://mms/" + idMMS + "/addr");
			Cursor curAddr = getContentResolver().query(uriAddr, null,
					"type=137", null, null);

			if (curAddr.moveToNext()) {
				String address = curAddr.getString(curAddr
						.getColumnIndex("address"));
				if (address.contentEquals("insert-address-token")) {
					Cursor curAddr2 = getContentResolver().query(uriAddr, null,
							"type=151", null, null);
					if (curAddr2.moveToNext()) {
						address = curAddr2.getString(curAddr2
								.getColumnIndex("address"));
					}
				}

				for (String email : emails) {

					if (email.equals(address)) {
						mms.setNombreContacto(address);
						mms.set_fecha(date);
						mms.set_telfono(address);
						mms.set_tipoLlamada(imagen);
						acciones.add(mms);

					}

				}

			}
		}
		 adapter = new LogAdapter(acciones);
		if (settingOrden.getInt("filtroAcciones", 0) != 0) {

			for (LogAccion acc : acciones) {

				if (acc.get_tipoLlamada() == settingOrden.getInt("filtroAcciones", 0) || acc.get_tipoLlamada() == settingOrden.getInt("filtroAcciones2", 0)) {
					filtrados.add(acc);
				}

			}
			
			adapter.setAcciones(filtrados);
			 setListAdapter(adapter); 

		} else {
			 setListAdapter(adapter);
		}
		
		
		  if(settingOrden.getInt("ordenAcciones", 0)!=1){
		  Collections.sort(adapter.getAcciones()); Collections.reverse(adapter.getAcciones()); } else{
		  Collections.sort(adapter.getAcciones(), new ComparadorContacto()); }
		  
		  adapter.setAcciones(adapter.getAcciones());
		  setListAdapter(adapter);
		

		s.setOnItemSelectedListener(new OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> parentView,
					View selectedItemView, int position, long id) {
				SharedPreferences.Editor prefEditor = settingOrden.edit();
				switch (position) {
				case 0:
					if (filtroFlag) {
						prefEditor.putInt("filtroAcciones", 0);
						adapter.setAcciones(acciones);
					}
					filtroFlag = true;
					break;
				case 1:
					filtrados.clear();
					for (LogAccion acc : acciones) {
						if (acc.get_tipoLlamada() == R.drawable.ic_call_log_list_outgoing_call || acc.get_tipoLlamada() == R.drawable.ic_call_log_list_incoming_call) {
							filtrados.add(acc);
						}
					}
					prefEditor.putInt("filtroAcciones",
							R.drawable.ic_call_log_list_outgoing_call);
					prefEditor.putInt("filtroAcciones2",
							R.drawable.ic_call_log_list_incoming_call);
					adapter.setAcciones(filtrados);
					break;

				case 2:
					filtrados.clear();
					for (LogAccion acc : acciones) {
						if (acc.get_tipoLlamada() == R.drawable.ic_sms_log_list_outgoing_sms || acc.get_tipoLlamada() == R.drawable.ic_sms_log_list_incoming_sms) {
							filtrados.add(acc);
						}
					}
					prefEditor.putInt("filtroAcciones",
							R.drawable.ic_sms_log_list_outgoing_sms);
					prefEditor.putInt("filtroAcciones2",
							R.drawable.ic_sms_log_list_incoming_sms);
					adapter.setAcciones(filtrados);
					break;

				case 3:
					filtrados.clear();
					for (LogAccion acc : acciones) {
						if (acc.get_tipoLlamada() == R.drawable.ic_mms_log_list_outgoing_mms) {
							filtrados.add(acc);
						}
					}
					prefEditor.putInt("filtroAcciones",
							R.drawable.ic_mms_log_list_outgoing_mms);
					adapter.setAcciones(filtrados);
					break;

				case 4:
					filtrados.clear();
					for (LogAccion acc : acciones) {
						if (acc.get_tipoLlamada() == R.drawable.ic_web_log_list_outgoing_web) {
							filtrados.add(acc);
						}
					}
					prefEditor.putInt("filtroAcciones",
							R.drawable.ic_web_log_list_outgoing_web);

					adapter.setAcciones(filtrados);
					break;

				default:
					break;
				}
				prefEditor.commit();
				setListAdapter(adapter);

			}

			@Override
			public void onNothingSelected(AdapterView<?> parentView) {

			}

		}

		);

		getListView().setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View view,
					int position, long arg3) {

				mMoreIv = (ImageView) view.findViewById(R.id.log_i_more);
				mMoreIv.setImageResource(R.drawable.ic_list_more_selected2);

			}

		});

	}

	protected Dialog onCreateDialog(int id) {

		switch (id) {
		case DIALOG_ORDENAR:
			final CharSequence[] items = { "Fecha", "Tipo" };
			return new AlertDialog.Builder(LogActivity.this)
					.setTitle(R.string.text_dialog_ordenar)
					.setSingleChoiceItems(items,
							settingOrden.getInt("ordenAcciones", 0),
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int whichButton) {
									SharedPreferences.Editor prefEditor = settingOrden
											.edit();
									if (whichButton == 0) {
										Collections.sort(adapter.getAcciones());
										Collections.reverse(adapter
												.getAcciones());
										prefEditor.putInt("ordenAcciones", 0);
										prefEditor.commit();
									} else {
										Collections.sort(adapter.getAcciones(),
												new ComparadorContacto());
										prefEditor.putInt("ordenAcciones", 1);
										prefEditor.commit();
									}
									adapter.setAcciones(adapter.getAcciones());
									setListAdapter(adapter);
									dialog.dismiss();
								}
							})

					.show();

		}
		return null;
	}

	class Holder {
		ImageView log_iconContact;
		TextView log_txtContactName;
		TextView log_txtnumber;
		TextView log_txtfechaLlamada;
		ImageView log_tipoLlamada;
	}

	class LogAdapter extends BaseAdapter {

		private LayoutInflater _inflater;
		private ArrayList<LogAccion> _acciones;

		public LogAdapter(ArrayList<LogAccion> _llamadas) {
			super();
			this._acciones = _llamadas;
			_inflater = LayoutInflater.from(LogActivity.this);
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return _acciones.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return _acciones.get(position);
		}

		@Override
		public long getItemId(int position) {
			return _acciones.get(position).get_id();

		}

		public void setAcciones(ArrayList<LogAccion> acciones) {
			_acciones = acciones;
		}

		public ArrayList<LogAccion> getAcciones() {
			return _acciones;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {

			Holder holder;
			if (convertView == null) {
				convertView = _inflater.inflate(R.layout.log_item, null);
				holder = new Holder();

				holder.log_iconContact = (ImageView) convertView
						.findViewById(R.id.log_Cimage);
				holder.log_txtContactName = (TextView) convertView
						.findViewById(R.id.log_txtContactName);
				holder.log_txtnumber = (TextView) convertView
						.findViewById(R.id.log_txtContactNumber);
				holder.log_txtfechaLlamada = (TextView) convertView
						.findViewById(R.id.log_txtfechaLlamada);
				holder.log_tipoLlamada = (ImageView) convertView
						.findViewById(R.id.log_tipoLlamada);

				convertView.setTag(holder);

			} else {
				holder = (Holder) convertView.getTag();
			}
			LogAccion log = _acciones.get(position);

			int imagen = log.get_tipoLlamada();
			holder.log_iconContact
					.setImageResource(R.drawable.ic_contact_item2);
			holder.log_iconContact.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					mQuickAction.show(v);

				}
			});
			holder.log_txtContactName.setText(contactoNom);
			holder.log_txtnumber.setText(log.get_telfono());
			holder.log_txtfechaLlamada.setText(log.get_fecha());
			holder.log_tipoLlamada.setImageResource(imagen);
			return convertView;
		}
	}
}
